# -*-coding:utf-8-*-

# !/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import smtplib
import time
from email.mime.text import MIMEText
from email.header import Header
import re
from config.globalconfig import report_path


class SendMail(object):
    def __init__(self):
        self.host = "smtp.qq.com"
        self.user = "751347936@qq.com"
        self.password = "dcgvqrtodnjsbbig"
        self.sender = '751347936@qq.com'
        self.receivers = ['sqm0307@163.com']

    def get_report(self):
        dirs = os.listdir(report_path)
        sort_dirs = sorted(dirs, key=lambda i: re.findall(r"\d+[-]\d+[-]\d+[_]\d+[_]\d+[_]\d+", i), reverse=True)
        return sort_dirs[0]

    def take_messages(self):
        new_report = self.get_report()
        with open(os.path.join(report_path, new_report), "rb") as f:
            msg = f.read()
        self.message = MIMEText(msg, 'html', 'utf-8')
        # self.message["Content-Type"] = 'application/octet-stream'
        self.message['From'] = Header("sqm", 'utf-8')
        self.message['To'] = Header("测试", 'utf-8')
        subject = '自动化测试报告'
        self.message['Subject'] = Header(subject, 'utf-8')  # 邮箱标题
        self.message['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')

    def send_mail(self):
        self.take_messages()
        try:
            smtpObj = smtplib.SMTP()
            smtpObj.connect(self.host, 25)
            smtpObj.login(self.user, self.password)
            smtpObj.sendmail(self.sender, self.receivers, self.message.as_string())
            smtpObj.close()
            print("邮件发送成功")
        except smtplib.SMTPException:
            print("Error: 无法发送邮件")


if __name__ == "__main__":
    email = SendMail()
    email.send_mail()
